package zone.czh.woi.woim.server.channel.initializer;

import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.MessageToMessageDecoder;
import lombok.AllArgsConstructor;
import lombok.Data;
import zone.czh.woi.woim.base.channel.codec.PacketHandler;
import zone.czh.woi.woim.base.channel.constant.ChannelHandlerName;
import zone.czh.woi.woim.base.obj.vo.Packet;
import zone.czh.woi.woim.server.channel.initializer.manager.HandlerManager;

import java.util.List;

/**
*@ClassName: ServerChannelInitializer
*@Description: None
*@author woi
*/
@Data
@AllArgsConstructor
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {


    private HandlerManager handlerManager;
    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();

        pipeline.addLast(ChannelHandlerName.PROTOCOL_INITIALIZER,handlerManager.protocolInitializer());

        //===heartbeat
        pipeline.addLast(ChannelHandlerName.IDLE_STATE_HANDLER,handlerManager.idleStateHandler());
        pipeline.addLast(ChannelHandlerName.CONNECTION_STATE_HANDLER,handlerManager.connectionStateHandler());
        //===

        //===protocol decoder
        //===

        //===payload to packet
        pipeline.addLast(ChannelHandlerName.PAYLOAD_HANDLER,handlerManager.payloadHandler());
        //===

        //===auth
        pipeline.addLast(ChannelHandlerName.AUTH_HANDLER,handlerManager.authHandler());//鉴权
        pipeline.addLast(ChannelHandlerName.BARRIER,handlerManager.barrier());
        //===


        //===protocol encoder
        //===

        //===payload to protocol
        pipeline.addLast(ChannelHandlerName.PAYLOAD_ENCODER,handlerManager.payloadEncoder());
        //===


        //===obj 2 payload
        pipeline.addLast(handlerManager.privateMsgEncoder());
        pipeline.addLast(handlerManager.groupMsgEncoder());
        pipeline.addLast(handlerManager.intentEncoder());
        //===

        //===packet handler
        pipeline.addLast(handlerManager.privateMsgHandler());
        pipeline.addLast(handlerManager.groupMsgHandler());

        List<PacketHandler> customHandlers = handlerManager.customHandlers();
        if (customHandlers!=null){
            for (MessageToMessageDecoder<Packet> customHandler:customHandlers){
                pipeline.addLast(customHandler);
            }
        }
        //===
    }
}
